<?php
class Delivery_Model_Mailer	
{
	private $_configuration;
	private $_transport;

	const PRIORITY_LOW = 1;
	const PRIORITY_NORMAL = 2;
	const PRIORITY_HIGH = 3;
	
    public function __construct()
	{
	    $config = Zend_Registry::get( 'configuration' );
	    $this->_configuration = $config->mail;
	}	
	
    public function send( $mailQueue )
    {
	    $transport = $this->getTransport();
	    
	    $mail = new Zend_Mail( 'utf-8' );
	    
	    $mail->addTo( $mailQueue->to );
	    $mail->setFrom( $mailQueue->fromAddress, $mailQueue->fromName );
	    $mail->setReplyTo( $mailQueue->fromAddress, $mailQueue->fromName );
	    $mail->setBodyHtml( $mailQueue->body, 'utf-8') ;
	    $mail->setSubject( $mailQueue->subject ) ;
	    
	    $mail->send( $transport );
	    
	}
	
    public function queue( $mail, $priority = self::PRIORITY_NORMAL)
    {
	    $mailQueue = new Delivery_Model_MailQueue();
	    $mapper = Delivery_Model_Factory::mapper('MailsQueue');
        $filter = new Zend_Filter_StripNewlines;
	    
	    
        $mailQueue->priority    = $priority;
        $mailQueue->fromName    = $mail->fromName;
        $mailQueue->fromAddress = $mail->fromAddress;
        $mailQueue->to          = $mail->to;
        $mailQueue->subject     = $mail->subject;
        $mailQueue->body        = $filter->filter($mail->body);
        $mailQueue->trySent     = 0;  
        
        $mapper->save( $mailQueue );
	}
	
    public function getTransport()
    {
	    if ( $this->_transport ){
	        return $this->_transport;
	    }
        
        $config = array(
			'auth' => $this->_configuration->auth,
			'username' => $this->_configuration->username,
			'password' => $this->_configuration->password,
			'port' => $this->_configuration->port,
			'ssl' => 'tls'
		);
		
		$transport = new Zend_Mail_Transport_Smtp($this->_configuration->server, $config);

		return $transport;
	}
	
 	public function queueSms( $to, $text)
    {
	    $queueSms = new Delivery_Model_QueueSms();
	    $mapper = Delivery_Model_Factory::mapper('QueueSms');
	    
        $queueSms->to   = $to;
        $queueSms->text = $text;
        
        $mapper->save( $queueSms );
	}
	
	public function sendSms( $host, $user, $pass, $from, $mailQueue )
    {
	   //;https://www.justvoip.com/myaccount/sendsms.php?username=xxxxxxxxxx​&password=xxxxxxxxxx&from=xxxxxxxxxx&to=xxxxxxxxxx&text=xxxxxxxxx
	   $uri = Zend_Uri::factory( $host ); 
	   $uri->setQuery(array(
	   		'username' => $user,
		   	'password' => $pass,
		   	'from' => $from,
		   	'to' => $mailQueue->to,
		   	'text' => $mailQueue->text
		));
		
		file_get_contents( $uri->getUri() );
		
	}
	
}